package servlet;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.softserveinc.autorent.model.CarPhoto;

@WebServlet("/DisplayPictureServlet")
public class DisplayPictureServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	byte[] bytes = null;
	@PersistenceContext(unitName = "jpa")
	private EntityManager em;
       

    public DisplayPictureServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		try{
			Query query = em.createNamedQuery("CarPhoto.findById");
			query.setParameter("id", Integer.parseInt(id));
			List <?> list = query.getResultList();
				if(list.size() > 0){
					CarPhoto carPhoto = (CarPhoto) list.get(0);
					bytes = carPhoto.getPhoto();
					response.reset();
					response.setContentType("image/jpg");
					response.getOutputStream().write(bytes, 0, bytes.length);
					response.getOutputStream().flush();
					response.getOutputStream().close();
					bytes = null;
				}
		} catch ( Exception e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
